package com.showde.shoppingmall.activity;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.FrameLayout.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

import com.kim.androidbase.imageloader.ImageLoader;
import com.showde.shoppingmall.R;
import com.showde.shoppingmall.ShoppingMallApplication;
import com.showde.shoppingmall.business.logic.CallbackData;
import com.showde.shoppingmall.business.logic.ProductCollectionLogic;
import com.showde.shoppingmall.business.logic.ProductLogic;
import com.showde.shoppingmall.business.logic.UICallbackInterface;
import com.showde.shoppingmall.db.ProductCollectionDBCommand;
import com.showde.shoppingmall.db.ProductDBCommand;
import com.showde.shoppingmall.db.ProductDescDBCommand;
import com.showde.shoppingmall.db.ShoppingcartDBCommand;
import com.showde.shoppingmall.domain.Product;
import com.showde.shoppingmall.domain.ProductDesc;
import com.showde.shoppingmall.domain.ShoppingCart;
import com.showde.shoppingmall.utils.ActivityDispatch;
import com.showde.shoppingmall.utils.ConformDialogUtils;
import com.showde.shoppingmall.utils.ConformDialogUtils.DialogCallback;
import com.showde.shoppingmall.utils.ToastUtils;

public class ProductDetailsActivity extends BaseActivity implements ViewFactory {

	private static final String TAG = "ProductDetailsActivity";

	private static final int MSG_TOSHOPPINGCART = 0x1001;
	private static final int MSG_COLLECTION_SUCCESS = 0x1002;
	private static final int MSG_COLLECTION_FAIL = 0x1003;
	private static final int MSG_REFRESH_PAGE = 0x1004;

	private static long TIME_INTERVAL = 1000 * 3;

	private ImageView productIconShow; // 商品图片轮换

	private TextView salePrice; // 折扣价txt_saleprice
	private TextView marketPrice; // 市场价txt_marketprice
	private TextView postfee; // 邮费txt_mailfee
	private TextView point; // 积分 txt_point
	private TextView title;// 商品标题
	private WebView webView; // 商品描述

	private TextView productAttributeTextView; // 商品属性
	private TextView productDescTextView; // 商品描述信息

	private RelativeLayout productAttributeLayout;
	private RelativeLayout productDescLayout;

	private ImageButton ibtnCollect;// 收藏
	private ImageButton ibtnAddToShoppingcart; // 加入购物车
	private ImageButton ibtnBuyRightnow; // 立即购买

	private Button btnPriceProtect; // 价格保护
	private Button btnCompensate;// 贵就赔

	private String productId;
	private Product product;
	private ProductDesc productDesc;

	private ProductDBCommand productDBCommand;
	private ProductDescDBCommand productDescDBCommand;
	private ShoppingcartDBCommand shoppingcartDBCommand;

	private ImageLoader imageLoader;

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_TOSHOPPINGCART:
				ActivityDispatch.openNewActivity(ProductDetailsActivity.this,
						ShoppingcarActivity.class,
						ActivityDispatch.getActivityGroup(groupTag),
						"ProductDetailsActivity", groupTag);
				break;
			case MSG_COLLECTION_SUCCESS:
				ToastUtils.showToast(ProductDetailsActivity.this, "收藏成功...");
				break;
			case MSG_COLLECTION_FAIL:
				ToastUtils.showToast(ProductDetailsActivity.this, "收藏失败...");
				break;
			case MSG_REFRESH_PAGE:
				doInResume();
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		super.onResume();
		doInResume();
	}

	private void doInResume() {
		if (productId != null) {
			fetchProductDescFromNet();
		}
		if (product != null) {
			imageLoader.displayImage(product.getProductLogo(), productIconShow);
			refreshData();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ibtn_collect:
			if (!ShoppingMallApplication.userSession.isSessionAvailable()) {
				// ToastUtils.showToast(this, "请登录吉鸿商城...");
				ActivityDispatch.openNewActivity(this, LoginActivity.class,
						ActivityDispatch.getActivityGroup(groupTag),
						"ProductDetailsActivity", groupTag);
				return;
			}
			ProductCollectionDBCommand dbCommand = new ProductCollectionDBCommand(
					this);
			if (dbCommand.exist(productId)) {
				ToastUtils.showToast(this, "该商品已收藏...");
				return;
			}
			ProductCollectionLogic.collectionProduct(this, productId,
					new UICallbackInterface() {

						@Override
						public void onSuccess(CallbackData data) {
							if (data != null) {
								handler.sendEmptyMessage(MSG_COLLECTION_SUCCESS);
							}
						}

						@Override
						public void onError(String errorMsg) {
							handler.sendEmptyMessage(MSG_COLLECTION_FAIL);
						}
					});
			break;
		case R.id.ibtn_putinto_shoppingcart:
			if (shoppingcartDBCommand.exist(productId)) {
				ConformDialogUtils.getInstance(
						ActivityDispatch.getActivityGroup(groupTag))
						.showConformDialog("该商品已添加到购物车，马上去购物车",
								new DialogCallback() {

									@Override
									public void onPositiveCall() {
										handler.sendEmptyMessage(MSG_TOSHOPPINGCART);
									}
								});
				return;
			}
			ShoppingCart t = new ShoppingCart();
			t.setProductId(productId);
			shoppingcartDBCommand.add(t);
			t = null;
			ActivityDispatch.openNewActivity(this, ShoppingcarActivity.class,
					ActivityDispatch.getActivityGroup(groupTag),
					"ProductDetailsActivity", groupTag);
			break;
		case R.id.txt_productattribute:
		case R.id.txt_productdesc:
			changeView(v.getId());
			break;
		case R.id.ibtn_buy_rightnow:
			ToastUtils.showToast(this, "该功能暂时不能使用...");
			break;
		case R.id.ibtn_price_protect:
			ActivityDispatch.openNewActivity(this, PriceProtectActivity.class,
					ActivityDispatch.getActivityGroup(groupTag),
					"ProductDetailsActivity", groupTag);
			break;
		case R.id.ibtn_gjp:
			ActivityDispatch.openNewActivity(this, CompensateActivity.class,
					ActivityDispatch.getActivityGroup(groupTag),
					"ProductDetailsActivity", groupTag);
			break;
		}
	}

	@Override
	protected void initParam() {
		productId = intent.getStringExtra(ActivityDispatch.PRODUCT_ID);
		if (productId != null) {
			if (productDBCommand == null) {
				productDBCommand = new ProductDBCommand(this);
			}
			product = productDBCommand.query(productId);
			if (product == null || product.getProductID() == null) {
				ProductLogic.fetchProductSummary(this, productId,
						new UICallbackInterface() {

							@Override
							public void onSuccess(CallbackData data) {
								if (data != null) {
									product = productDBCommand.query(productId);
									handler.sendEmptyMessage(MSG_REFRESH_PAGE);
								}
							}

							@Override
							public void onError(String errorMsg) {

							}
						});
			}
			if (productDescDBCommand == null) {
				productDescDBCommand = new ProductDescDBCommand(this);
			}
			productDesc = productDescDBCommand.query(productId);
			Log.d(TAG, "product:" + product);
			Log.d(TAG, "productDesc:" + productDesc);
		}
		imageLoader = new ImageLoader(this);

		if (shoppingcartDBCommand == null) {
			shoppingcartDBCommand = new ShoppingcartDBCommand(this);
		}
	}

	@Override
	protected void initView() {
		setContentView(R.layout.product_details);
		productIconShow = (ImageView) findViewById(R.id.product_icon);
		// productIconShow.setFactory(this);
		ibtnCollect = (ImageButton) findViewById(R.id.ibtn_collect);
		ibtnCollect.setOnClickListener(this);
		ibtnAddToShoppingcart = (ImageButton) findViewById(R.id.ibtn_putinto_shoppingcart);
		ibtnAddToShoppingcart.setOnClickListener(this);
		ibtnBuyRightnow = (ImageButton) findViewById(R.id.ibtn_buy_rightnow);
		ibtnBuyRightnow.setOnClickListener(this);
		btnPriceProtect = (Button) findViewById(R.id.ibtn_price_protect);
		btnPriceProtect.setOnClickListener(this);
		btnCompensate = (Button) findViewById(R.id.ibtn_gjp);
		btnCompensate.setOnClickListener(this);

		productAttributeLayout = (RelativeLayout) findViewById(R.id.rl_productdetails);
		productDescLayout = (RelativeLayout) findViewById(R.id.rl_productattribute);

		title = (TextView) findViewById(R.id.txt_producttitle);
		webView = (WebView) findViewById(R.id.wv_productdesc);
		webView.loadData("Product Description.", "text/html", "utf-8");

		productAttributeTextView = (TextView) findViewById(R.id.txt_productattribute);
		productDescTextView = (TextView) findViewById(R.id.txt_productdesc);
		productAttributeTextView.setOnClickListener(this);
		productDescTextView.setOnClickListener(this);

	}

	@Override
	public View makeView() {
		ImageView imageView = new ImageView(this);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		imageView.setLayoutParams(params);
		return imageView;
	}

	private void changeView(int viewId) {
		switch (viewId) {
		case R.id.txt_productattribute:
			productAttributeLayout.setVisibility(View.VISIBLE);
			productDescLayout.setVisibility(View.GONE);
			productAttributeTextView
					.setBackgroundResource(R.drawable.product_details_tab_pressed);
			productDescTextView
					.setBackgroundResource(R.drawable.product_details_tab);
			break;
		case R.id.txt_productdesc:
			productAttributeLayout.setVisibility(View.GONE);
			productDescLayout.setVisibility(View.VISIBLE);
			productAttributeTextView
					.setBackgroundResource(R.drawable.product_details_tab);
			productDescTextView
					.setBackgroundResource(R.drawable.product_details_tab_pressed);
			break;
		}
	}

	private void fetchProductDescFromNet() {
		ProductLogic.fetchProductDetails(this, productId,
				new UICallbackInterface() {

					@Override
					public void onSuccess(CallbackData data) {

					}

					@Override
					public void onError(String errorMsg) {

					}
				});
	}

	/**
	 * 刷新页面数据
	 */
	private void refreshData() {
		title.setText(product.getProductTitle());
		webView.loadData(productDesc.getProductDescDesc(), "text/html", "utf-8");
	}

}